﻿using System.ComponentModel;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using RIBA.Helper;
using Riba.MVVMSL;
using RIBA.Web;

namespace RIBA
{
	public class Login_VM : ViewModelBase
	{
		public RelayCommand CommandOk { get; private set; }

		private string _userName;
		public string UserName
		{
			get { return _userName; }
			set { SetPropertyValue(ref _userName, value, () => UserName); }
		}

		private string _password;
		public string Password
		{
			get { return _password; }
			set { SetPropertyValue(ref _password, value, () => Password); }
		}

		private string _status = TextRes.TestUser.Replace("\\n", "\n");
		public string Status
		{
			get { return _status; }
			set { SetPropertyValue(ref _status, value, () => Status); }
		}

		private bool _isNoOperationPending = true;
		public bool IsNoOperationPending
		{
			get { return _isNoOperationPending; }
			set { SetPropertyValue(ref _isNoOperationPending, value, () => IsNoOperationPending); }
		}

		public Login_VM()
		{
			CommandOk = new RelayCommand
				(
					cmdPar =>
					{
						if (DesignerProperties.IsInDesignTool)
							return;

						IsBusy = true;
						Status = "";

						IsNoOperationPending = false;
						var loginParameters = new LoginParameters(UserName, Password);
						WebContext.Current.Authentication.Login(loginParameters, LoginOperation_Completed, null);
					}
				) { IsEnabled = true };
		}

		private void LoginOperation_Completed(LoginOperation loginOperation)
		{
			IsNoOperationPending = true;
			IsBusy = false;

			if (loginOperation.LoginSuccess)
			{
				RaiseCloseChildWindowView();
				return;
			}

			var errMsg = OperationBaseErrorHandler.GetErrMsg(loginOperation);
			if (errMsg != "")
			{
				Status = errMsg;
				return;
			}

			Status = TextRes.UserOrPasswordWrong;
		}
	}
}
